package com.lw.leetcode.tree.c;

import com.lw.leetcode.tree.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 1028. 从先序遍历还原二叉树
 *
 * @Author liw
 * @Date 2021/5/20 13:27
 * @Version 1.0
 */
public class RecoverFromPreorder {


    public static void main(String[] args) {
        RecoverFromPreorder test = new RecoverFromPreorder();
        TreeNode treeNode = test.recoverFromPreorder("1-2--3--4-5--6--7");
        System.out.println(treeNode);
    }

    private int item = 1;
    private int end;
    private List<Integer> valList;
    private List<Integer> dList;

    public TreeNode recoverFromPreorder(String traversal) {
        List<Integer> valList = new ArrayList<>();
        List<Integer> dList = new ArrayList<>();

        int value = 0;
        int d = 0;
        boolean flag = true;
        dList.add(0);
        for (byte b : traversal.getBytes()) {
            if (b == 45) {
                d++;
                flag = false;
            } else {
                if (flag) {
                    value = value * 10 + (b - 48);
                } else {
                    valList.add(value);
                    dList.add(d);
                    value = (b - 48);
                    d = 0;
                }
                flag = true;
            }
        }
        valList.add(value);
        this.valList = valList;
        this.dList = dList;
        this.end = valList.size();
        TreeNode root = new TreeNode(valList.get(0));
        find(root, 0);
        return root;
    }

    private void find(TreeNode node, int n) {
        if (item == end) {
            return;
        }
        int a = item;
        int last = dList.get(n) + 1;
        int td = dList.get(a);
        if (last == td) {
            item++;
            Integer value = valList.get(a);
            TreeNode c = new TreeNode(value);
            node.left = c;
            find(c, a);
        }
        if (item == end) {
            return;
        }
        a = item;
        td = dList.get(a);
        if (last == td) {
            item++;
            Integer value = valList.get(a);
            TreeNode c = new TreeNode(value);
            node.right = c;
            find(c, a);
        }
    }

}
